#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
分析puma_param.json中的参数，更新paramset_en_cn.json
"""

import json
import sys
from collections import defaultdict

def load_json_file(file_path):
    """加载JSON文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"错误: 无法读取文件 {file_path} - {e}")
        sys.exit(1)

def save_json_file(data, file_path):
    """保存JSON文件"""
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"成功保存文件: {file_path}")
    except Exception as e:
        print(f"错误: 无法保存文件 {file_path} - {e}")
        sys.exit(1)

def extract_param_names_from_puma(puma_data):
    """从puma_param.json中提取所有参数名"""
    param_pairs = {}
    all_en_params = set()
    all_cn_params = set()
    
    if isinstance(puma_data, list):
        for model in puma_data:
            if isinstance(model, dict) and 'paramSet' in model:
                for param in model['paramSet']:
                    if isinstance(param, dict):
                        param_name_en = param.get('param_name_en', '').strip()
                        param_name_cn = param.get('param_name_cn', '').strip()
                        
                        if param_name_en:
                            all_en_params.add(param_name_en)
                            
                        if param_name_cn:
                            all_cn_params.add(param_name_cn)
                            
                        # 如果英文和中文都存在且不相同，记录配对
                        if param_name_en and param_name_cn and param_name_en != param_name_cn:
                            param_pairs[param_name_en] = param_name_cn
    
    return param_pairs, all_en_params, all_cn_params

def main():
    """主函数"""
    # 加载现有文件
    puma_data = load_json_file('puma_param.json')
    existing_mappings = load_json_file('paramset_en_cn.json')
    
    # 提取puma中的参数名
    param_pairs, all_en_params, all_cn_params = extract_param_names_from_puma(puma_data)
    
    print(f"从puma_param.json中提取到 {len(param_pairs)} 个英中文配对")
    print(f"总共找到 {len(all_en_params)} 个英文参数名")
    print(f"总共找到 {len(all_cn_params)} 个中文参数名")
    
    # 合并到现有映射中
    updated_mappings = existing_mappings.copy()
    new_count = 0
    
    for en_param, cn_param in param_pairs.items():
        if en_param not in updated_mappings:
            updated_mappings[en_param] = cn_param
            new_count += 1
            print(f"新增: {en_param} -> {cn_param}")
        elif updated_mappings[en_param] != cn_param:
            print(f"更新: {en_param}: {updated_mappings[en_param]} -> {cn_param}")
            updated_mappings[en_param] = cn_param
    
    # 查找只有英文没有中文翻译的参数
    missing_translations = []
    for en_param in all_en_params:
        if en_param not in updated_mappings:
            missing_translations.append(en_param)
    
    print(f"\n找到 {len(missing_translations)} 个缺少中文翻译的英文参数:")
    for param in sorted(missing_translations):
        print(f"  - {param}")
    
    # 将缺少翻译的参数添加到映射中，使用英文作为临时翻译
    for en_param in missing_translations:
        updated_mappings[en_param] = en_param  # 临时使用英文作为中文
        new_count += 1
    
    # 按字母顺序排序
    sorted_mappings = dict(sorted(updated_mappings.items()))
    
    # 保存更新后的文件
    save_json_file(sorted_mappings, 'paramset_en_cn.json')
    
    print(f"\n总结:")
    print(f"- 原有参数映射: {len(existing_mappings)} 个")
    print(f"- 新增参数映射: {new_count} 个")
    print(f"- 更新后总数: {len(sorted_mappings)} 个")
    print(f"- 需要人工翻译的参数: {len(missing_translations)} 个")

if __name__ == "__main__":
    main()
